﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace AutoTool
{
    public static class EntityGenerator
    {
        public static void GenerateEntityClass(string tableName, Dictionary<string, string> columns)
        {
            // 当前运行路径（例如 bin\Debug\netcoreapp3.1\）
            string currentPath = AppDomain.CurrentDomain.BaseDirectory;

            // 从当前路径退回到 news-sys 的根目录
            string projectRootPath = Path.Combine(currentPath, "..\\..\\..\\..");

            // 拼接目标路径 NewsEntity\Models\
            string targetPath = Path.Combine(projectRootPath, "NewsEntity", "Models");

            // 转换为标准绝对路径
            targetPath = Path.GetFullPath(targetPath);

            // 类名与文件路径
            var className = tableName;
            var filePath = @$"{targetPath}\{className}.cs";

            // 生成属性代码
            var properties = string.Join(Environment.NewLine, columns.Select(column =>
            {
                var columnName = column.Key;
                var columnType = ConvertToCSharpType(column.Value);
                return $"        public {columnType} {columnName} {{ get; set; }}";
            }));

            // 生成完整代码
            var code = $@"
using System;

namespace NewsEntity.Models
{{
    public class {className}
    {{
{properties}
    }}
}}";

            // 创建目标文件夹（如果不存在）
            if (!Directory.Exists(targetPath))
            {
                Directory.CreateDirectory(targetPath);
            }

            // 写入文件
            File.WriteAllText(filePath, code);
        }

        private static string ConvertToCSharpType(string sqlType)
        {
            // 将 SQL 数据类型映射到 C# 数据类型
            return sqlType.ToLower() switch
            {
                "int" => "int",
                "bigint" => "long",
                "smallint" => "short",
                "tinyint" => "byte",
                "bit" => "bool",
                "decimal" => "decimal",
                "numeric" => "decimal",
                "float" => "double",
                "real" => "float",
                "datetime" => "DateTime",
                "smalldatetime" => "DateTime",
                "date" => "DateTime",
                "time" => "TimeSpan",
                "char" => "string",
                "varchar" => "string",
                "text" => "string",
                "nchar" => "string",
                "nvarchar" => "string",
                "ntext" => "string",
                "uniqueidentifier" => "Guid",
                _ => "string" // 默认使用 string 类型
            };
        }
    }
}
